package com.isunland.managesystem.base;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.ViewConfiguration;
import android.widget.Toast;
import cn.jpush.android.api.JPushInterface;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Request.Method;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.bugtags.library.Bugtags;
import com.isunland.managesystem.BuildConfig;
import com.isunland.managesystem.R;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.AppManager;
import com.isunland.managesystem.common.MyApplication;
import com.isunland.managesystem.common.RequestManager;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.BaseParams;
import com.isunland.managesystem.ui.TestActivity;
import com.isunland.managesystem.utils.LogUtil;
import com.isunland.managesystem.utils.MyStringUtil;
import com.isunland.managesystem.utils.MyUtils;
import com.umeng.analytics.MobclickAgent;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

/**
 * volley联网封装类.
 *
 * @author wangyanan
 */
public class BaseVolleyActivity extends AppCompatActivity {
  protected static final String TAG = "BaseActivity";
  private static final int MENU_ITEM_DEV = 1123;
  private static String mRoleTypeFlag;
  public FragmentActivity mActivity;
  public BaseParams mBaseParams;

  /**
   * 所有请求都需要的类别参数.
   *
   * @param flag 是人员角色类型,在入口guidemenuFragment类中点击子项传递不同的人员角色类型.
   * 需要时静态的 ,因为 需要这个人员角色类型伴随这个模块的所有接口.
   */
  public static void setRoleTypeFlag(String flag) {
    mRoleTypeFlag = flag;
  }

  /**
   * 带参数的Activity
   *
   * @param fragment 当前Fragment
   * @param requestCode 请求码
   * @param params 参数.
   * @param activity 要启动的Activity
   */
  public static void newInstance(Fragment fragment, Class<? extends BaseVolleyActivity> activity,
      BaseParams params, int requestCode) {
    if (fragment == null || activity == null) return;
    Intent i = new Intent(fragment.getActivity(), activity);
    i.putExtra(BaseFragment.EXTRA_PARAMS, params);
    fragment.startActivityForResult(i, requestCode);
  }

  /** 使用context启动activity,注意不会走fragment的onActivityResult方法 */
  public static void newInstance(AppCompatActivity context,
      Class<? extends BaseVolleyActivity> activity, BaseParams params, int requestCode) {
    if (context == null || activity == null) return;
    Intent i = new Intent(context, activity);
    i.putExtra(BaseFragment.EXTRA_PARAMS, params);
    context.startActivityForResult(i, requestCode);
  }

  public static void newInstance(Fragment fragment, String activityName, BaseParams params,
      int requestCode) {
    if (fragment == null || MyStringUtil.isEmpty(activityName)) return;
    Intent i = new Intent();
    i.setClassName(fragment.getActivity().getPackageName(), activityName);
    i.putExtra(BaseFragment.EXTRA_PARAMS, params);
    fragment.startActivityForResult(i, requestCode);
  }

  /** 使用context启动activity,注意不会走fragment的onActivityResult方法 */
  public static void newInstance(AppCompatActivity context, String activityName, BaseParams params,
      int requestCode) {
    if (context == null || MyStringUtil.isEmpty(activityName)) return;
    Intent i = new Intent();
    i.setClassName(context.getPackageName(), activityName);
    i.putExtra(BaseFragment.EXTRA_PARAMS, params);
    context.startActivityForResult(i, requestCode);
  }

  /**
   *
   */
  // @Override
  // public void onStop() {
  // super.onStop();
  // RequestManager.cancelAll(this);
  // }
  @Override protected void onDestroy() {
    RequestManager.cancelAll(this);
    AppManager.getAppManager().finishActivity(this);
    super.onDestroy();
  }

  @Override protected void onCreate(Bundle arg0) {
    mBaseParams = (BaseParams) getIntent().getSerializableExtra(BaseFragment.EXTRA_PARAMS);
    mActivity = this;
    LogUtil.i("displayed=", mActivity.getClass().getSimpleName());
    // 将每个界面都加入,方便统一管理.
    AppManager.getAppManager().addActivity(this);
    setOverflowShowingAlways();
    super.onCreate(arg0);
  }

  //public Response.ErrorListener errorListener() {
  //    return new Response.ErrorListener() {
  //
  //        @Override
  //        public void onErrorResponse(VolleyError error) {
  //
  //            Log.e(TAG, "volleyError=" + error.toString(), error);
  //            Toast.makeText(BaseVolleyActivity.this, R.string.noConnectionToServer, Toast.LENGTH_SHORT).show();
  //            MyUtils.dismissDialog();
  //        }
  //    };
  //}

  public void executeRequest(Request<?> request) {

    RequestManager.addRequest(request, this);
  }

  /**
   * 请求
   * 如果是列表的时候，需要打印log时传递6，再上一层，默认传递5.
   *
   * @param isList 是否是列表
   * @param isNeedRoleType 是否需要人员角色类型,默认true
   */
  @SuppressWarnings("unused") public void volleyPost(String url, HashMap<String, String> params,
      VolleyResponse response, boolean isList, boolean isNeedRoleType) {
    if (!MyUtils.isNetLink(this)) {
      Toast.makeText(this, R.string.network_error, Toast.LENGTH_SHORT).show();
      MyUtils.dismissDialog();
      return;
    }
    if (mRoleTypeFlag == null) mRoleTypeFlag = ""; //有的接口是不需要人员角色类型的,如果不需要就不要传.
    if (isNeedRoleType) params.put("roleTypeFlag", mRoleTypeFlag); /*用于移动端动态配置,*/
    if (MyUtils.isDevelopMode(MyApplication.getAppContext()) && MyUtils.isMock()) {
      params.put("id", "11");
    }
    //只打印接口,不打印host.
    LogUtil.i("url=", MyStringUtil.replaceAll(url, ApiConst.getUrlMain(), ""));
    LogUtil.d("params=", params);
    LogUtil.i("postman=", MyStringUtil.paramsToPostman(params));
    LogUtil.i("paramsJson=", MyStringUtil.toJson(params));
    //不打印通用参数.每次找参数太烦.
    params.put("mobileConfig", "android");
    params.put("mobileBuildFlavor", BuildConfig.FLAVOR);
    params.put("mobileVersionCode", MyStringUtil.valueOf(MyUtils.getVersionCode(mActivity)));
    params.put("mobileVersionName", MyUtils.getVersionName(mActivity));
    //		Bugtags.setUserData("url",url);
    response.setContext(BaseVolleyActivity.this);
    StringRequest request = getStringRequest(url, params, response);
    request.setRetryPolicy(RequestManager.getRetryPolicy());
    executeRequest(request);
    // MyUtils.showDialogLoading(this);
  }

  public void volleyPost(String url, HashMap<String, String> params, VolleyResponse response) {
    volleyPost(url, params, response, false, true);
  }

  public void volleyPost(String url, HashMap<String, String> params, VolleyResponse response,
      boolean isList) {
    volleyPost(url, params, response, isList, true);
  }

  private StringRequest getStringRequest(String url, final HashMap<String, String> params,
      VolleyResponse response) {

    // 如果response为空,初始化response
    if (response == null) {
      LogUtil.i("Empty Response");
      response = new VolleyResponse() {

        @Override public void onVolleyResponse(String arg0) {
        }

        @Override public void onVolleyError(VolleyError arg0) {

        }
      };
    }
    return new StringRequest(Method.POST, url, response, response) {
      @Override protected Map<String, String> getParams() throws AuthFailureError {
        // 如果参数为空,初始化参数.

        HashMap<String, String> baseParams = new HashMap<>();
        baseParams.putAll(params);
        //				Bugtags.setUserData("params",baseParams.toString());
        return baseParams;
      }
    };
  }

  /**
   * bugtags回调.
   */
  @Override protected void onResume() {
    super.onResume();
    if (MyUtils.isBugTags(mActivity)) {

      Bugtags.onResume(this);
    }
    if (BuildConfig.IS_UMENTANAYLYSIS) {

      MobclickAgent.onResume(this);
    }
    JPushInterface.onResume(this);
  }

  @Override protected void onPause() {
    super.onPause();

    if (MyUtils.isBugTags(mActivity)) {
      Bugtags.onPause(this);
    }

    if (BuildConfig.IS_UMENTANAYLYSIS) {

      MobclickAgent.onPause(this);
    }

    JPushInterface.onPause(this);
  }

  //	public boolean checkPermission(String permission){
  //
  //		// 动态获取权限,兼容android6.0以上.
  //				if (Build.VERSION.SDK_INT >= 23) {
  //
  //					int checkNetPermission = ContextCompat.checkSelfPermission(this,
  //							permission);
  //
  //
  //					if (checkNetPermission != PackageManager.PERMISSION_GRANTED
  //							) {
  //
  //						ActivityCompat.requestPermissions(this,
  //								new String[] { permission }, 1);
  //						return false;
  //					}
  //
  //				}
  //				return true;
  //	}

  @Override public boolean dispatchTouchEvent(MotionEvent event) {
    try {
      if (MyUtils.isBugTags(mActivity)) Bugtags.onDispatchTouchEvent(this, event);
      //捕获异常，报错信息java.lang.IllegalArgumentException: pointerIndex out of range，
      return super.dispatchTouchEvent(event);
    } catch (Exception e) {
      e.printStackTrace();
    }
    return false;
  }

  /**
   * 修复在某些有实体按键的手机上,overflowmenu不显示的问题
   */

  private void setOverflowShowingAlways() {
    try {
      ViewConfiguration config = ViewConfiguration.get(this);
      //通过反射的方式获取key
      Field menuKeyField = ViewConfiguration.class.getDeclaredField("sHasPermanentMenuKey");
      menuKeyField.setAccessible(true);
      menuKeyField.setBoolean(config, false);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  @Override public boolean onCreateOptionsMenu(Menu menu) {
    if (MyUtils.isDevelopMode(mActivity)) {//开发模式下,显示测试类.
       /*
         * add()方法的四个参数，依次是：
         * 1、组别，如果不分组的话就写Menu.NONE,
         * 2、Id，这个很重要，Android根据这个Id来确定不同的菜单
         * 3、顺序，那个菜单现在在前面由这个参数的大小决定，参数越小，显示的越前
         * 4、文本，菜单的显示文本
         */
      menu.add(Menu.NONE, MENU_ITEM_DEV, 100, getString(R.string.devOption))
          .setIcon(R.drawable.ic_dev_72)
          .setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
    }
    return super.onCreateOptionsMenu(menu);
  }

  @Override public boolean onOptionsItemSelected(MenuItem item) {
    if (item.getItemId() == MENU_ITEM_DEV) startActivity(new Intent(this, TestActivity.class));
    return super.onOptionsItemSelected(item);
  }
}
